package core

import (
	"encoding/json"
	"os"
	"runtime"
	"sync"
)

type Config struct {
	NAServerAddr string
	DownloadDir  string
}

var (
	instance_config *Config
	once_config     sync.Once
)

func GetConfig() *Config {
	once_config.Do(func() {
		// 数据总线，用于应用间通信
		instance_config = &Config{}
	})
	return instance_config
}

func (c *Config) LoadConfig() error {
	configFileName := ""
	switch runtime.GOOS {
	case "darwin":
		configFileName = "Config_Darwin.json"
	case "windows":
		configFileName = "Config_Windows.json"
	}
	data, err := os.ReadFile(configFileName)
	if err != nil {
		return err
	}

	var config Config
	if err := json.Unmarshal(data, &config); err != nil {
		return err
	}
	c.DownloadDir = config.DownloadDir
	c.NAServerAddr = config.NAServerAddr
	return nil
}
func (c *Config) SaveConfig() error {
	configFileName := ""
	switch runtime.GOOS {
	case "darwin":
		configFileName = "Config_Darwin.json"
	case "windows":
		configFileName = "Config_Windows.json"
	}
	config := Config{DownloadDir: c.DownloadDir, NAServerAddr: c.NAServerAddr}
	data, err := json.Marshal(config)
	if err != nil {
		return err
	}

	return os.WriteFile(configFileName, data, 0644)
}
